<template>
  <div>
    <div class="topBtn">
      <div class="sizeBig">
        <span>生产开工</span>
      </div>
      <div>
        <el-button @click="searchPageReset" style="height:39px" type="primary">查询</el-button>
        <el-button @click="start" type="primary">
          <i class="icon_start"></i>开始打印
        </el-button>
        <el-button @click="pause" type="primary">
          <i class="icon_suspend"></i>任务暂停
        </el-button>
        <el-button @click="cancel" type="primary">
          <i class="icon_cancel"></i>任务取消
        </el-button>
      </div>
    </div>
    <div class="message">
      <p class="character">1.点击【开始】按钮，即可控制系统打印任务服务，开始添加照片文件到打印机缓存区，待打印机开机后识别缓存区文件开始按顺序打印。</p>
      <p class="character">
        2.打印机因为跟线体已经设置关联，如果需要更换打印机请在<span class="skip">“排程管理”</span>更换排程线体即可，若是排程正在生产中，请先点击【任务取消】按钮，再进行换线操作。
      </p>
      <p class="character">
        3.【暂停】是让添加文件到打印任务区的服务暂停，方便换纸、维修保养等操作；而【任务取消】则是把已经添加到任务区的文件撤回上一步。
        <span class="skip">查看帮助文档</span>
      </p>
    </div>
    <div class="inputcontent">
      <el-input @keydown.native.enter="searchPageReset" class="inSearch" placeholder="请输入内容"
                v-model="search"></el-input>
      <el-select @change="searchPageReset" placeholder="状态" v-model="value">
        <el-option
          :key="item.value"
          :label="item.label"
          :value="item.value"
          v-for="item in options"
        ></el-option>
      </el-select>
      <el-select @change="getLine" clearable placeholder="线体" v-model="LineId">
        <el-option
          :key="index"
          :label="item.Name"
          :value="item.LineId"
          v-for="(item,index) in linebodyData"
        ></el-option>
      </el-select>
      <el-select @change="searchPageReset" clearable filterable placeholder="排程" v-model="OrderAutoPlanId">
        <el-option
          :key="index"
          :label="item.Name"
          :value="item.OrderAutoPlanId"
          v-for="(item,index) in planData"
        ></el-option>
      </el-select>


      <el-date-picker
        :default-value="dateRange"
        :picker-options="pickerOptions"
        @change="searchPageReset"
        end-placeholder="结束日期"
        format="yyyy-MM-dd HH:mm"
        range-separator="-"
        start-placeholder="开始日期"
        type="daterange"
        v-model="dateRange"
        value-format="yyyy-MM-dd HH:mm">
      </el-date-picker>

      <!-- <div class="need" style="float:right;margin-right:20px;">
        需要产能：
        <span>9.3H</span>
      </div> -->
    </div>
    <div class="tableCotent">
      <Table :mainDataLoading="mainDataLoading" :reset="reset" v-on:changeData="changedata"
             v-on:getId="getListId"></Table>
    </div>

    <!-- 分页 -->
    <div class="block">

      <el-pagination
        :current-page="currentPage"
        :page-size="size"
        :page-sizes="[10,20,50,100]"
        :total="TotalNum"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <div class="sum">
        <el-tag>{{`照片总数 : ${sum}`}}</el-tag>
      </div>
    </div>

    <!-- 开始打印弹出框  width="760px"  -->
    <el-dialog :visible.sync="startDialogVisible" center title="输出打印控制台" width="1400px">
      <el-form :inline="true" :model="searchFormData" label-width="85px" ref="searchDataForm" size="small">

        <!--        <el-form-item label="线体名" prop="LineId">-->
        <!--          <el-select @change="searchRequest" @clear="searchRequest" clearable style="width: 200px"-->
        <!--                     v-model="searchFormData.LineId">-->
        <!--            <el-option :key="item.LineId" :label="item.Name" :value="item.LineId"-->
        <!--                       v-for="(item,index) in linebodyData"></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->

        <el-form-item label="材料" prop="LineId">
          <el-cascader :props="materialCascade"
                       :value="-1"
                       @change="materialCascadeChange"
                       clearable/>
        </el-form-item>

        <el-form-item label="订单计划名" prop="OrderAutoPlanName">
          <el-input @keyup.enter.native="searchRequest" clearable icon="el-icon-search" style="width: 200px"
                    v-model="searchFormData.OrderAutoPlanName"/>
        </el-form-item>

        <el-form-item label="模版名" prop="BoardModelID">
          <el-select @change="searchRequest" @clear="searchRequest" clearable style="width: 200px"
                     v-model="searchFormData.BoardModelID">
            <el-option :key="item.BoardModelID" :label="item.Name" :value="item.BoardModelID"
                       v-for="(item,index) in  boardModelData"></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="状态筛选" prop="PrintStatus">

          <el-select @change="searchRequest" @clear="searchRequest" clearable style="width: 200px"
                     v-model="searchFormData.PrintStatus">
            <el-option :key="item.LineId" :label="item.label" :value="item.value"
                       v-for="(item,index) in [
                         {label:'全部',value:''},
                         {label:'暂停',value:0},
                         {label:'启动',value:1},
                       ]"></el-option>
          </el-select>

          <!--          <el-switch-->
          <!--            @change="searchRequest"-->
          <!--            :active-value="1"-->
          <!--            :inactive-value="0"-->
          <!--            active-text="开"-->
          <!--            inactive-text="关"-->
          <!--            v-model="searchFormData.PrintStatus"/>-->
        </el-form-item>
      </el-form>

      <el-table
        :data="startTableData"
        @selection-change="handleSelectionChange"
        class="table start-print"
        height="400px"
        style="width: 100%;borderTop: 1px solid #ccc;"
        v-loading="lineTableLoading"
      >
        <el-table-column
          align="center"
          type="selection"
          width="50">
        </el-table-column>

        <el-table-column align="center" label="名称" prop="OrderAutoPlanName"/>
        <el-table-column align="center" label="线体" width="200">
          <template scope="scope">
            <el-select disabled placeholder="请选择" v-model="scope.row.LineId">
              <el-option
                :key="index"
                :label="item.Name"
                :value="item.LineId"
                v-for="(item,index) in options1"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column align="center" label="相纸类型" width="380">
          <template scope="scope" style="width:100%">
            <!--            <el-select placeholder="请选择" style="width:360px" v-model="scope.row.BoardModelID">-->
            <!--              <el-option-->
            <!--                :key="index"-->
            <!--                :label="item.Name"-->
            <!--                :value="item.MaterialItemID"-->
            <!--                v-for="(item,index) in materialData"-->
            <!--              ></el-option>-->
            <!--            </el-select>-->

            <el-select disabled filterable v-model="scope.row.BoardModelID">
              <el-option :key="item.BoardModelID" :label="item.Name" :value="item.BoardModelID"
                         v-for="(item,index) in  boardModelData"></el-option>
            </el-select>

          </template>
        </el-table-column>

        <!--        <el-table-column align="center" label="打印状态" prop="DisplayPrintStatus">-->
        <!--          <template scope="scope">-->
        <!--            <el-tag>{{scope.row['DisplayPrintStatus']}}</el-tag>-->
        <!--          </template>-->
        <!--        </el-table-column>-->

        <el-table-column align="center" label="最大" prop="MaxNum"/>
        <el-table-column align="center" label="最小" prop="MinNum"/>
        <el-table-column align="center" label="全部数量" prop="AllCount"/>

        <el-table-column align="center" label="控制打印" prop="ControlStatus" width="150">
          <template slot-scope="scope">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              @change="nv => void changePrintStatus(nv,scope.row)"
              active-text="开"
              inactive-text="关" v-model="scope.row.PrintStatus"></el-switch>
          </template>

          <template slot="header" slot-scope="scope">
            <!--
               -->
            <el-switch
              :active-value="1"
              :inactive-value="0"
              @change="nv => void changeAllPrintStatus({multipleSelection,newState:nv})"
              v-model="globalSwitchFlag"></el-switch>
          </template>

        </el-table-column>

      </el-table>
      <!--      <div @click="add1">-->
      <!--        <span class="skip">添加</span>-->
      <!--      </div>-->
      <!--      <div class="botBtn">-->
      <!--        <el-button @click="startDialogVisible=false" class="quxiao">取消</el-button>-->
      <!--        <el-button @click="onSubmit" type="primary">保存</el-button>-->
      <!--      </div>-->

      <Pagination :auto-scroll="false" :limit.sync="searchFormData.limit"
                  :page.sync="searchFormData.page"
                  :total="total"
                  @pagination="pageChange"
      />
    </el-dialog>
  </div>
</template>

<script>
  import { getAllLineList, GetKMAnd750Line, getLineList } from '@/api/linebody' // 请求线体数据
  import {
    getProductionPlanList, //获取排程列表
    getPrintControlList, // 打印控制列表查询
    commitPrintControl, // 提交打印控制器
    // startPrintProductionPlan,   //开始打印
    pausePrintProductionPlan, //暂停打印
    cancelPrintProductionPlan, //取消打印
    getMaterialItemList, //物料列表查询
    getOrderAutoPlanListOfLine,
    GetAutoProductionPlansForPrint,
    ModifyOrderAutoPlanPrintStatus,
    ModifyOrderAutoPlanListPrintStatus, GetLineMaterialItem  //排程配置查询
  } from '@/api/startWorking'
  import Table from './components/startWorkingTable'
  import { Agent } from 'http'
  import { delay } from '@/utils/autoSearch'
  import { deleteNullValue, ERR_OK } from '@/utils/commons'
  import {  GetBoardModel } from '@/api/order'
  import Pagination from '@/components/ATheFridayClub/Pagination'
  import form from '@/mixins/form'
  import moment from 'moment'

  function getDefaultDate() {
    const start = new Date()
    return [
      moment(start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)).format('YYYY-MM-DD HH:mm:ss')
      , moment(new Date(new Date((new Date(new Date().setHours(23))).setMinutes(59))).setSeconds(0))
        .format('YYYY-MM-DD HH:mm:ss')
    ]
  }

  export default {
    name: 'startWorking',
    components: {
      Table, Pagination
    },
    mixins: [form],
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '最近3天',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 3)
              picker.$emit('pick', [start, end])
            }
          }
          ]
        },
        tableData: [],
        ControlStatus: true,
        reset: [],
        mainDataLoading: false,
        globalSwitchFlag: 0,
        options: [
          {
            value: -1,
            label: '所有'
          },
          {
            value: 0,
            label: '创建'
          },
          {
            value: 1,
            label: '合成中'
          },
          {
            value: 2,
            label: '已合成'
          },
          {
            value: 3,
            label: '打印中'
          },
          {
            value: 4,
            label: '打印暂停'
          },
          {
            value: 5,
            label: '打印取消'
          },
          {
            value: 6,
            label: '打印完成'
          },
          {
            value: 7,
            label: '暂停'
          }
        ],
        options1: [],
        lineData: [],
        OrderAutoPlanId: [],
        dateRange: getDefaultDate(),
        planData: [],
        materialData: [],
        item: [],
        jsonItem: [],
        search: '',
        value: -1,
        LineId: '',
        sum: 0,
        currentPage: 1, //初始页
        size: 10,
        TotalNum: 0,//数据总条数

        checkIds: [],
        addlist: [],
        startDialogVisible: false,
        lineTableLoading: false,
        searchFormData: {
          MatertialID: '',
          OrderAutoPlanName: '',
          LineId: '',
          BoardModelID: '',
          limit: 10,
          page: 1
        },
        startTableData: [],
        total: 0,
        boardModelData: [],
        linebodyData: [],
        multipleSelection: [],
        materialCascade: {
          lazy: true,
          // emitPath: false,
          async lazyLoad(node, resolve) {
            const { level, value } = node
            if (level === 0) {
              const { Result } = await GetKMAnd750Line({ keyName: '', page: 1, pageSize: 99999999 })
              resolve(Result.map(({ LineId, Name }) =>
                ({ value: LineId, label: Name, leaf: false })))
            } else if (level === 1) {
              const { Result } = await GetLineMaterialItem({ lineId: value })
              resolve(Result.map(({ MaterialItemID, Name }) =>
                ({ value: MaterialItemID, label: Name, leaf: true })))
            }
          }
        }
      }
    },

    created() {
      this.input()
      this.onput()
      this.getPlan()

      GetBoardModel({ PageSize: 999999, PageNum: 1 }).then(res => {
        if (parseInt(res.Code) === ERR_OK) {
          this.boardModelData = res.Result.Items
          // this.boardData = res.Result.Items
        }
      })

      GetKMAnd750Line({ keyName: '', page: 1, pageSize: 99999999 }).then(res => {
        if (parseInt(res.Code) === ERR_OK) {
          this.linebodyData = res.Result
        }
      })

    },
    watch: {
      //用来监听页面变量的改变
      search() {
        delay(() => {
          this.init()
        }, 300)
      }
    },
    mounted() {
      this.init()
    },
    methods: {
      materialCascadeChange([omit, MatertialID = ''] = []) {
        this.searchFormData.MatertialID = MatertialID
        this.searchRequest()
      },
      pageChange({ page, limit }) {
        this.searchFormData.limit = limit
        this.searchFormData.page = page
        this.start()
      },

      async changeAllPrintStatus({ multipleSelection, newState = 0 } = {}) {
        try {
          if (!multipleSelection.length) {
            return this.$notify.warning({ title: '请至少选择一项' })
          }
          multipleSelection.forEach(v => v.PrintStatus = newState)
          const { Code } = await ModifyOrderAutoPlanListPrintStatus(
            multipleSelection.map(({ OrderAutoPlanId }) => ({ OrderAutoPlanId, PrintStauts: newState }))
          )
          if (Code === ERR_OK) {
            const h = this.$createElement
            this.$notify.success({
              title: '打印状态修改成功', message: h('div', { style: { display: 'flex', flexWrap: 'wrap' } }, [
                multipleSelection.map(
                  ({ OrderAutoPlanName }) => h('el-tag', { style: { margin: '5px' } }, OrderAutoPlanName)
                ),
                h('span', `已成功切换打印状态为${newState === 0 ? '关闭' : '开启'}`)
              ])
            })
          }
        } catch (e) {
          console.log(e)
        }
      },

      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      async changePrintStatus(PrintStatus, { OrderAutoPlanId = -1 } = {}) {

        try {
          const { Code } = await ModifyOrderAutoPlanPrintStatus({
            OrderAutoPlanId, PrintStauts: PrintStatus
          })
          if (Code === ERR_OK) {
            this.$notify.success({ title: PrintStatus === 0 ? '切换打印状态为关闭' : '切换打印状态为开启' })
          }
        } catch (e) {
          console.log(e)
        }
      },

      //分页
      handleSizeChange(size) {
        this.size = size
        this.init()
      },
      handleCurrentChange(currentPage) {
        this.currentPage = currentPage
        this.init()
      },
      //数据初始化
      init() {
        this.mainDataLoading = true
        const [stTime, endTime] = this.dateRange ?? []
        let data = {
          keyName: this.search,
          status: this.value,
          lineID: this.LineId,
          orderAutoPlanId: this.OrderAutoPlanId,
          page: this.currentPage,
          pageSize: this.size,
          stTime, endTime
        }
        getProductionPlanList(deleteNullValue(data)).then(res => {
          if (parseInt(res.Code) === 1) {
            this.reset = res.Result.Items
            this.TotalNum = res.Result.TotalNum
            this.getSum()
          }
        }).finally(() => {
          this.mainDataLoading = false
        })

      },
      // 求当前页照片之和
      getSum() {
        this.sum = 0
        for (var i = 0; i < this.reset.length; i++) {
          let num = this.reset[i].SnCount
          let nums = parseInt(num)
          this.sum += nums
        }
        // console.log(this.sum)
      },
      getListId(listId) {
        this.checkIds = listId
      },
      changedata(data) {
        this.addlist = data
        // console.log(this.addlist);
      },
      searchPageReset() {
        this.currentPage = 1
        this.init()
      },
      // 根据所选线体查询数据
      getLine() {
        this.searchPageReset()
        // 根据所选线体查询排程
        getOrderAutoPlanListOfLine({ lineId: parseInt(this.LineId) }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.planData = res.Result
          }
        })
      },
      // 线体数据
      input() {
        getAllLineList({ keyName: '', lineType: 1 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.lineData = res.Result
          }
        })
        getLineList({ keyName: '', page: 1, pageSize: 1000 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.options1 = res.Result.Items
          }
        })
      },
      // 物料数据
      onput() {
        getMaterialItemList({ keyName: '' }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.materialData = res.Result
          }
        })
      },
      // 获取排程
      getPlan() {
        getOrderAutoPlanListOfLine({ lineId: 0 }).then(res => {
          if (parseInt(res.Code) === 1) {
            this.planData = res.Result
          }
        })
      },

      searchRequest() {
        this.searchFormData.page = 1
        this.start()
      },
      //开始打印
      async start() {
        // this.startDialogVisible = true;
        // getPrintControlList({ status: -1 }).then(res => {
        //   if (parseInt(res.Code) === 1) {
        //     res.Result.forEach((el, idx) => {
        //       this.item = el;
        //       if (el.ControlStatus === 1) {
        //         el.ControlStatus = true;
        //       } else {
        //         el.ControlStatus = false;
        //       }
        //     });
        //     this.tableData = res.Result;
        //   }
        // });
        try {
          this.lineTableLoading = true
          const { page: PageIndex, limit: PageSize, ..._ } = this.searchFormData
          this.startDialogVisible = true
          const { Code, Result, Message } = await GetAutoProductionPlansForPrint({
            PageSize, PageIndex, ..._
          } |> deleteNullValue)
          if (Code === ERR_OK) {
            const { Items, TotalNum } = Result
            this.startTableData = Items
            this.total = TotalNum
          }
        } catch (e) {
          console.log(e)
        } finally {
          this.lineTableLoading = false
        }

      },
      //提交打印控制器
      onSubmit() {
        this.jsonItem = []
        for (var i = 0; i < this.tableData.length; i++) {
          if (this.tableData[i].ControlStatus == true) {
            this.tableData[i].ControlStatus = 1
          } else {
            this.tableData[i].ControlStatus = 0
          }
          // if(this.tableData[i].LineId ===this.item.LineId&&
          // this.tableData[i].MaterialItemID===this.litem.MaterialItemID&&
          // this.tableData[i].ControlStatus===this.item.ControlStatus){
          //     return
          // }else{
          var list = {
            PrintControlID: this.tableData[i].PrintControlID,
            LineId: this.tableData[i].Line.LineId,
            MaterialItemID: this.tableData[i].MaterialItem.MaterialItemID,
            ControlStatus: this.tableData[i].ControlStatus
          }
          this.jsonItem.push(list)
          // }
        }
        console.log(this.jsonItem)
        commitPrintControl({ jsonString: JSON.stringify(this.jsonItem) }).then(
          res => {
            if (parseInt(res.Code) === 1) {
              this.$message({
                type: 'success',
                message: '成功'
              })
            }
            this.startDialogVisible = false
          }
        )
      },
      //新增一行
      add1() {
        console.log(this.tableData.length)
        this.tableData.push({
          PrintControlID: 0,
          Line: { LineId: '' },
          MaterialItem: { MaterialItemID: '' },
          ControlStatus: ''
        })
      },
      //暂停打印
      pause() {
        if (this.addlist.length < 1) {
          this.$message('请勾选需要暂停打印的数据')
        } else {
          let listid = ''
          this.checkIds.forEach(el => {
            listid += el + ','
          })
          listid = listid.substr(0, listid.length - 1)
          pausePrintProductionPlan({ strProductionPlanId: listid }).then(res => {
            if (parseInt(res.Code) === 1) {
              this.$message('暂停打印')
            }
            this.init()
          })
        }
      },
      //取消打印
      cancel() {
        if (this.addlist.length < 1) {
          this.$message('请勾选需要取消打印的数据')
        } else {
          let listid = ''
          this.checkIds.forEach(el => {
            listid += el + ','
          })
          listid = listid.substr(0, listid.length - 1)
          cancelPrintProductionPlan({ strProductionPlanId: listid }).then(res => {
            if (parseInt(res.Code) === 1) {
              this.$message('取消打印')
            }
            this.init()
          })
        }
      }
    }
  }
</script>

<style lang="scss">
  .start-print {
    /deep/ td {
      border: none !important;
    }
  }
</style>

<style lang="scss" scoped>
  .sizeBig {
    font-size: 16px;
    font-weight: 600;
  }

  .topBtn {
    height: 60px;
    width: 98%;
    margin: 0 auto;
    line-height: 60px;
    display: flex;
    justify-content: space-between;

    .icon_start {
      display: inline-block;
      width: 14px;
      height: 14px;
      margin-right: 2px;
      margin-bottom: 2px;
      background: url("image/renwukaishi.png") no-repeat;
      vertical-align: middle;
    }

    .icon_suspend {
      display: inline-block;
      width: 14px;
      height: 14px;
      margin-right: 2px;
      margin-bottom: 2px;
      background: url("image/zanting.png") no-repeat;
      vertical-align: middle;
    }

    .icon_cancel {
      display: inline-block;
      width: 14px;
      height: 14px;
      margin-right: 2px;
      margin-bottom: 2px;
      background: url("image/renwuquxiao.png") no-repeat;
      vertical-align: middle;
    }
  }

  .message {
    width: 98%;
    margin: 0 auto;
    /*height: 130px;*/
    background: rgba(255, 255, 255, 1);
    border: 1px solid rgba(238, 238, 238, 1);
    font-size: 14px;

    .character {
      margin: 20px 0 21px 20px;
      color: #999999;

      .skip {
        color: #0095ff;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }

  .inputcontent {
    width: 98%;
    /*height: 80px;*/
    margin: 10px;
    position: relative;
    /*padding-top: 21px;*/
    box-sizing: border-box;

    .iconSearch {
      position: absolute;
      left: 277px;
      top: 30px;
      width: 20px;
      height: 20px;
      background-image: url("./image/搜索.png");
      background-repeat: no-repeat;
      cursor: pointer;
    }

    .inSearch {
      width: 308px;
      height: 40px;
    }

    .need {
      line-height: 40px;

      span {
        color: #f1022f;
        font-weight: 600;
      }
    }
  }

  .tableCotent {
    width: 98%;
    margin: 0 auto;
  }

  .block {
    .el-pagination {
      float: right;
      margin: 28px 20px 0 0;
    }

    .sum {
      float: right;
      margin: 29px 50px 0 0;

      h5 {
        font-size: 16px;
        font-weight: 400;
        float: left;
      }

      span {
        color: #f1022f;
        float: left;
      }
    }
  }

  .table {
    padding-top: 10px;
    overflow-x: hidden;

    .el-table-column {
      border-bottom: 2px solid #ccc;
    }
  }

  .skip {
    color: #0095ff;
    margin-left: 10px;
    cursor: pointer;
  }

  .botBtn {
    width: 40%;
    margin: 0 auto;
    margin-top: 20px;

    .quxiao {
      margin-right: 20px;
    }
  }

</style>

